package com.ycxh.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回视图工具类
 */
public class ViewResult {

    private static Logger logger = LoggerFactory.getLogger(ViewResult.class);

    private int code;

    private String msg;


    private Map<String, Object> data;

    private ModelAndView mav;

    private static ObjectMapper mapper = new ObjectMapper();

    public static ViewResult newInstance() {
        ViewResult instance = new ViewResult();
        return instance;
    }

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public Map<String, Object> getData() {
        return this.data;
    }

    public ViewResult code(int code) {
        this.code = code;
        return this;
    }

    public ViewResult msg(String msg) {
        this.msg = msg;
        return this;
    }

    public ViewResult failMsg(String msg) {
        this.code = ErrorMessageEnum.失败.getCode();
        this.msg = msg;
        return this;
    }

    public ViewResult put(String key, Object value) {
        if (this.data == null) {
            this.data = new HashMap();
        }
        this.data.put(key, value);
        return this;
    }

    public String json() {
        try {
            return mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            logger.error("json转换出现异常", e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

    public ModelAndView view(String pageName) {
        if (this.mav == null) {
            this.mav = new ModelAndView(pageName);
        }
        this.mav.addObject("result", this);
        return this.mav;
    }

    public ViewResult putAll(Map<String, Object> data) {
        if (this.data == null) {
            this.data = new HashMap();
        }
        this.data.putAll(data);
        return this;
    }

    public String redirect(String url) {
        return "redirect:" + url;
    }

    public String forward(String url) {
        return "forward:" + url;
    }

    public ModelAndView error() {
        return view("error404");
    }

}
